<?php

class DripController extends OauthAppController {
	
	var $components = array(
			'Session',
			'Cookie' => array('name' => 'MIAOCMS', 'time' => '+2 weeks'),
	);
	
	private $appid = '2364203459';
	private $secret = '8c3f3d8g0b53032d43014fe4d3159938';
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Hook->loadhook('UCenterHook');
	}
	
	
	public function login(){
	   $this->autoLayout = false;
	   $state = $_REQUEST['state'] ? $_REQUEST['state'] : 'drip';
	   header('location:http://weixin.drip.im/oauth2/authorize?client_id='.$this->appid.'&response_type=code&state='.$state.'&redirect_uri='.urlencode('http://www.135editor.com/oauth/drip/callback'));
	   exit;
	}
	
	public function callback(){
	    
	    $this->pageTitle = '水滴登录';
	
	    $code = $_REQUEST['code'];
	    $state =  $_REQUEST['state'];
	    
	    $appid = $this->appid;
	    $secret = $this->secret;
        $source = 'Drip';
        
	    $this->loadModel('User');
	    $this->loadModel('Oauthbind');
	    
	    $uid = 0; $oauth_bind = array();
	    
	    $this->set('source',$source);
	    $loginfo = $this->Session->read('DripLogin');
	    
	    if(empty($loginfo) || empty($loginfo['userinfo']) || $loginfo['code'] != $_REQUEST['code']) 
	    {
	        $url = 'https://api.drip.im/oauth2/access_token';
	        $params = array(
	            'client_id' => $appid,
	            'client_secret' => $secret,
	            'code' => $_REQUEST['code'],
	            'grant_type'=>'authorization_code',
	            'redirect_uri'=> 'http://www.135editor.com/oauth/drip/callback',
	        );
	        App::uses('RequestFacade', 'Network');
	        $response =  RequestFacade::post($url,$params);
	        
	        $ret  = json_decode($response->body,true);
	        if( $ret['access_token'] ){	            
	            
	            $userinfo_url = 'https://api.drip.im/oauth2/resources?access_token='.$ret['access_token'];
	            $response =  RequestFacade::get($userinfo_url);
	            $userinfo  = json_decode($response->body,true);
	            if(empty($userinfo) ){
	                echo $response;exit;
	            }
	            $this->Session->delete('DripLogin');
	            
	            $oauth_bind = $this->Oauthbind->find('first', array(
	                'conditions' => array(
	                    'oauth_openid' => $userinfo['user']['openid'],
	                    'source' => $source,
	                ),
	            ));
	            $uid = $oauth_bind['Oauthbind']['user_id'];
	
	            $userinfo['oauth_bind'] = $oauth_bind;
	            $userinfo['access_token'] = $ret['access_token'];
	            $userinfo['expires_in'] = $ret['expires_in'];
	            $userinfo['refresh_token'] = $ret['refresh_token'];
	            
	            $this->Session->write('drip_auth_user', $userinfo);
	            $this->Session->write('drip_auth_ret', $ret);
	        }
	        else{
	            echo $response;exit;
	        }
	    }
	    else{
	        //list($source,$userinfo) = $loginfo;
	        $source = $loginfo['source'];
	        $userinfo = $loginfo['userinfo'];
	        $oauth_bind = $userinfo['oauth_bind'];
	        $uid = $oauth_bind['Oauthbind']['user_id'];
	    }
	
	    // $db_user 为库中的用户信息， $userinfo 为oauth取的微信用户的信息
	    if( !empty($oauth_bind) && $uid ){
	        $current_time = date('Y-m-d H:i:s');
	        // 登录成功
	        $updateinfo = array(	           
	            'nickname' => $this->User->escape_string($userinfo['user']['nickname']),
	            'last_login' => $this->User->escape_string($current_time),
	        );
	        
	        $this->User->updateAll($updateinfo, array('id' => $uid));
	        
	        // 更新oauth信息
	        $oauth_bind['Oauthbind']['created'] = time();
	        $oauth_bind['Oauthbind']['oauth_token'] = $ret['access_token'];
	        $oauth_bind['Oauthbind']['expires'] = $ret['expires_in'];
	        $oauth_bind['Oauthbind']['refresh_token'] = $ret['refresh_token'];
	        $this->Oauthbind->save($oauth_bind);
	
	        $db_user = $this->User->find('first', array('conditions' => array('id'=> $uid)));
	
	        $this->Session->write('Auth.User', $db_user['User']);
	        $this->Cookie->write('Auth.User',array('id' => $db_user['User']['id'],'username' => $db_user['User']['username'],'email' => $db_user['User']['email'] ), true, 0);
	        $this->Session->delete('DripLogin');
// 	        $redirect = $this->Session->read('Auth.redirect');
// 	        if(empty($redirect)){
// 	            $redirect = $_GET['referer'] ? $_GET['referer'] : $_SERVER['HTTP_REFERER'];
// 	        }
// 	        $this->redirect($redirect);
	        $ret = $this->_ucenter_login(array('id'=>$uid));
	        
	        if($state == 'direct' || $state == 'redirect') {
	            $this->redirect('http://www.135editor.com/beautify_editor');
	        }
	        else{
	            @header('Content-Type:text/html; charset=UTF-8');
	            echo '<p>登录成功。如窗口没自动关闭，可手动关闭后刷新页面查看。</p>';
	            echo $ret['login_hook_msg'];
	            echo '<script>
    setTimeout(function(){
        window.opener.postMessage("loginSuccess","*");
        window.close();
        //window.opener.location.reload(true);
	},2000);</script>';
	        }
	        
	        
	        exit;
	    }
	    else{
	        $this->set('source',$source);
	        $this->set('userinfo',$userinfo);
	        $this->Session->write('DripLogin',array( 'source'=>$source, 'userinfo'=>$userinfo,'code'=>$_REQUEST['code'] ));
	        	
	        $this->layout = 'default';
	        $this->autoRender = true;
	    }
	}

    
    private function getUserInfo($openid,$access_token) {
    	$userinfo_url = 'https://api.drip.im/oauth2/resources?access_token='.$access_token;
    	$response =  RequestFacade::get($userinfo_url);
    	$userinfo  = json_decode($response->body,true);
    	if(empty($userinfo)){
    		echo 'drip api get userinfo error:';
    		echo $response;exit;
    	}
    	return $userinfo;
    }
        
    public function bind(){
    	
        if( empty($this->data['User']['email']) ) {
    		$this->__message(__('邮箱不能为空'), $referer);
    	}
    	
    	$source = 'Drip';
    	
    	$this->autoRender =  false;
    	$this->loadModel('User');$this->loadModel('Oauthbind');
    	$userinfo = $this->User->getUserByEmail($this->data['User']['email']);
    	
    	$login_token = $this->Session->read('drip_auth_ret');
    	$third_user = $this->Session->read('drip_auth_user');
    	
    	if(empty($login_token) || empty($third_user) ) {
    	    $this->redirect(array('action'=>'login'));
    	}
    	
    	if( !empty($userinfo) && Security::hash($this->data['User']['password'] , null, true) == $userinfo['User']['password'] ) {
    	
    	    $user_id = $userinfo['User']['id'];
    	    $this->loadModel('Oauthbind');
    	    $oauth_bind = $this->Oauthbind->find('first', array(
    	        'conditions' => array(
    	            'oauth_openid' => $third_user['user']['openid'],
    	            'user_id' => $user_id,
    	            'source' => $source,
    	        ),
    	    ));
    	
    	    if (empty($oauth_bind)) {
    	        $oauth_bind = array(
    	            'user_id' => $user_id,
    	            'oauth_openid' => $third_user['user']['openid'],
    	            'oauth_name' => $third_user['user']['nickname'],
    	            'expires' => $login_token['expires_in'],
    	            'refresh_token' => $login_token['refresh_token'],
    	            'oauth_token' => $login_token['access_token'],
    	            'source' => $source,
    	        );
    	        $this->Oauthbind->save($oauth_bind);
    	    } else {
    	        $oauth_bind['Oauthbind']['oauth_name'] = $third_user['user']['nickname'];
    	        $oauth_bind['Oauthbind']['updated'] = date('Y-m-d H:i:s');
    	        $oauth_bind['Oauthbind']['oauth_token'] = $login_token['access_token'];
    	        $this->Oauthbind->save($oauth_bind);
    	    }
    	    $this->Session->write('Auth.User', $userinfo['User']);
    	    $this->Cookie->write('Auth.User', array(
    	        'id' => $userinfo['User']['id'],
    	        'username' => $userinfo['User']['username'],
    	        'email' => $userinfo['User']['email'],
    	        'roles' => count($userinfo['User']['role_id']),
    	    ), true, 0);
    	
    	    $ret = $this->_ucenter_login(array('id'=>$user_id));
    	    @header('Content-Type:text/html; charset=UTF-8');
    	    echo '<p>绑定成功。如窗口没自动关闭，可手动关闭后刷新页面查看。</p>';
    	    echo $ret['login_hook_msg'];
    	    echo '<script>setTimeout(function(){
    	        window.opener.postMessage("loginSuccess","*");
    	        window.close();
    	        //window.opener.location.reload(true);
    	},2000);</script>';
    	
    	
    	    //             $referer =  $this->Session->read('oauth_referer');
    	    //             $referer ? $url = $referer :  $url='/';
    	    //             $this->redirect($url);
    	}
    	else{
    	    echo json_encode(array('ret' => -1,'error'=>'用户邮箱或者密码错误'));
    	}
    	exit;
    }
    
    public function register(){
        $this->autoRender = false;
        $login_token = $this->Session->read('drip_auth_ret');
        $third_user = $this->Session->read('drip_auth_user');
        
        if(empty($login_token) || empty($third_user)) { // session已过期，重新登录
            $this->redirect('/oauth/drip/login');
        }
    
        if ($third_user['gender'] == '男' || $third_user['gender']==1) {
            $gender = 1; //男
        } else {
            $gender = 0; //女
        }
        $current_time = date('Y-m-d H:i:s');
        
        $source = 'Drip';
    
        $referer =  $this->request->referer();
        if( empty($this->data['User']['email']) ) {
            $this->data['User']['email'] = substr(md5($third_user['user']['openid']),0,12).'@135editor.com';
        }
        if(empty($third_user['user']['nickname'])) {
            $third_user['user']['nickname'] = substr(md5($third_user['user']['openid']),0,12);
        }
        
        if( $this->data['User']['password'] != $this->data['User']['password_confirm']  ) {
            $this->__message(__('密码与确认密码不一致'), $referer);
        }
        $userinfo = array(
            'email' => $this->data['User']['email'],
            'password' => $_POST['password'] ? Security::hash($_POST['password'], null, true) : Security::hash(random_str(12), null, true),
            'username' => $third_user['user']['nickname'],
            'nickname' => $third_user['user']['nickname'],
            'screen_name' => $third_user['user']['nickname'],
            'image' => $third_user['headimgurl'],
            'sex' => $gender,
            'role_id' => 2,
            'last_login' => $current_time,
            'created' => $current_time,
            'city' => $third_user['city'],
            'province' => $third_user['province'],
            'activation_key' => md5(uniqid()),
            'status' => 1,
        );
        $this->loadModel('User');
        $this->loadModel('Oauthbind');
        if( $this->User->save($userinfo) ) {
    
            $userinfo['id'] = $user_id = $this->User->getLastInsertID();
            $this->Session->write('Auth.User', $userinfo);
            $this->Cookie->write('Auth.User', $userinfo, true, 0);
    
            $this->Session->delete('DripLogin');
            
            $oauth_bind = array(
                'user_id' => $user_id,
                'oauth_openid' => $third_user['user']['openid'],
                'oauth_name' => $third_user['user']['nickname'],
                'oauth_token' => $login_token['access_token'],
                'expires' => $login_token['expires_in'],
                'refresh_token' => $login_token['refresh_token'],
                'source' => $source,
            );
            $this->Oauthbind->save($oauth_bind);
    
            $ret = $this->_ucenter_login(array('id'=>$user_id));
            @header('Content-Type:text/html; charset=UTF-8');
            echo '<p>注册成功。如窗口没自动关闭，可手动关闭后刷新页面查看。</p>';
            echo $ret['login_hook_msg'];
            echo '<script>setTimeout(function(){window.opener.location.reload(true);window.close();},2000);</script>';
    
            //             $referer =  $this->Session->read('oauth_referer');
            //             $referer ? $url = $referer :  $url='/';
            //             $this->redirect($url);
        }
        else{
            $errors = $this->User->invalidFields();
            print_r($errors);
        }
        exit;
    
    }
    
    private function _ucenter_login($user){
        $this->Hook->loadhook('ScoreHook');
        $hook_results = $this->Hook->call('loginSuccess',array($user));
        $login_score = $hook_results['ScoreHook']; unset($hook_results['ScoreHook']); // 积分数不显示在提示消息中
        $user['login_hook_msg'] = implode("\r\n",$hook_results);
        return $user;
    }
}

?>